
#include"StdFIFO.h"
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdlib.h>
#define PATHSIZE 1024
struct StdFIFO
{
    int fd;
    char filePath[PATHSIZE];
};

FIFO *FIFOInit(const char *filePath, FMode mode)
{
    FIFO *f = (FIFO *)malloc(sizeof(FIFO));
    if(f==NULL)
    {
        perror("malloc:");
        return NULL;
    }
    strcpy(f->filePath, filePath);
    int ret = mkfifo(filePath, S_IRUSR | S_IWUSR);
    if(ret!=0)
    {
        perror("mkfifo:");
    }
    f->fd = open(filePath, mode);
    if(f->fd<0)
    {
        perror("open fifio:");
        free(f);
        return NULL;
    }
    return f;
}

bool ReadFromFIFO(FIFO *f, void *p, size_t size)
{
    if(read(f->fd, p, size)<=0)
    {
        perror("read fifo:");
        return false;
    }
    return true;
}

bool WriteFromFIFO(FIFO *f, void *p, size_t size)
{
    if(write(f->fd,p,size)<=0)
    {
        perror("write fifo:");
        return false;
    }
    return true;
}

void ClearFIFO(FIFO *f)
{
    //关文件描述符
    close(f->fd);
    //删除管道文件
    char cmd[2048] = {0};
    sprintf(cmd,"rm -f %s",f->filePath);
    system(cmd);
    //释放堆上内存
    free(f);
}
